<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryParamsRef"
      :inline="true"
      class="globalSerchFormStyle"
      label-width="68px"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="车队名称" prop="fleetName">
            <el-input
              v-model="queryParams.fleetName"
              placeholder="请输入车队名称"
              clearable
              size="small"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="主卡号" prop="cardNumber">
            <el-input
              v-model="queryParams.cardNumber"
              placeholder="请输入主卡号"
              clearable
              size="small"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="开通时间" prop="createdDate">
            <el-date-picker
              v-model="dateRangeCreatedDate"
              size="small"
              style="width: 190px"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 按钮 -->
    <el-row class="global_el_rowStyle" :gutter="10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="handleQuery"
          size="mini"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-refresh"
          @click="resetQuery"
          size="mini"
          plain
          >重置</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-plus"
          size="mini"
          plain
          @click="openRightDrawer('add', initTeamCardForm)"
          :disabled="$store.state.user.userLevel !== '1'"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-delete"
          size="mini"
          plain
          @click="gotoDeleteParentCard"
          :disabled="currentSelectList.length <= 0"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-download"
          size="mini"
          plain
          :disabled="currentSelectList.length !== 1"
          @click="exportQr"
          >导出二维码</el-button
        >
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table
      stripe
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      :default-sort="{ prop: 'date', order: 'descending' }"
      @selection-change="handleSelectChange"
    >
      <el-table-column type="selection" width="55" align="left">
      </el-table-column>

      <el-table-column
        prop="fleetName"
        label="车队名称"
        width="180"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="cardNumber"
        label="主卡号"
        width="180"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="balance"
        label="账户余额"
        sortable
        width="130"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="rechargeAmount"
        label="充值金额"
        sortable
        width="130"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="giftAmount"
        label="赠送金额"
        sortable
        width="130"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="contacts"
        label="联系人"
        width="130"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="third_organ_name"
        label="核销方式"
        width="180"
        :formatter="useTypeformatter"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="createdTime"
        label="开通时间"
        sortable
        width="150"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="updatedTime"
        label="最近一次修改时间"
        sortable
        width="150"
        show-overflow-tooltip
      >
      </el-table-column>

      <el-table-column prop="address" label="操作" fixed="right" width="450">
        <template slot-scope="scope">
          <el-button type="text" @click="openRightDrawer('detail', scope.row)"
            >查看</el-button
          >
          <el-button
            type="text"
            @click="openRightDrawer('edit', scope.row)"
            :disabled="$store.state.user.userLevel !== '1'"
            >编辑</el-button
          >
          <el-button
            type="text"
            @click="gotoSonCardConfig(scope.row)"
            :disabled="$store.state.user.userLevel !== '1'"
            >配置子卡</el-button
          >
          <el-button
            type="text"
            @click="goRecharge(scope.row)"
            :disabled="$store.state.user.userLevel !== '1'"
            >充值</el-button
          >
          <el-button type="text" @click="gotoRecycle(scope.row)"
            >回收</el-button
          >
          <el-button type="text" @click="goRechargeDetail(scope.row)"
            >充值明细</el-button
          >
          <el-button type="text" @click="goOrderDetail(scope.row)"
            >消费记录</el-button
          >
          <el-button
            type="text"
            @click="goUpdateBlance(scope.row)"
            :disabled="$store.state.user.userLevel != '1'"
            >余额调整</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增，编辑，查看 -->
    <TeamRightDrawer
      :teampListDialog.sync="teampListDialog"
      :operation="operation"
      :currentData="currentData"
      @reloadData="getList"
    ></TeamRightDrawer>

    <!-- 充值 -->
    <TeamRecharge
      :teamRechargeDialog.sync="teamRechargeDialog"
      :currentData="currentData"
      @reloadData="getList"
    ></TeamRecharge>

    <!-- 充值明细 -->
    <teamRechargeDetail
      :teamRechargeDetailDialog.sync="teamRechargeDetailDialog"
      :currentData="currentData"
      @reloadData="getList"
    ></teamRechargeDetail>

    <!-- 消费记录 -->
    <TeamOrderRecords
      :teamOrderListDialog.sync="teamOrderListDialog"
      :currentData="currentData"
    ></TeamOrderRecords>

    <!-- 导出二维码 -->
    <el-dialog title="导出二维码" :visible.sync="exportTeamCardQrVisible">
      <TeamCardQr
        :text="currentExportCardNumber"
        name="车队卡二维码"
        @downloadImg="downloadImg"
      ></TeamCardQr>
    </el-dialog>

    <!-- 配置子卡 -->
    <teamConfigSonCard
      :SonCardConfigDialog.sync="SonCardConfigDialog"
      :currentData="currentData"
      @reloadData="getList"
    ></teamConfigSonCard>

    <!-- 余额调整 -->
    <TeamUpdateBlance
      :teamUpdateBlanceDialog.sync="teamUpdateBlanceDialog"
      :currentData="currentData"
      @reloadData="getList"
    ></TeamUpdateBlance>

    <!-- 删除车队卡对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="delParentCardDialog"
      width="30%"
      :before-close="handleClose"
    >
      <span>确定删除所选中的车队卡吗</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delParentCardDialog = false">取 消</el-button>
        <el-button type="primary" @click="handleDeleteParentCard"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 回收子卡对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="recycleCardDialog"
      width="30%"
      :before-close="handleClose"
    >
      <span>
        确定回收
        <b>{{ currentData.fleetName }}</b>
        的余额及该车队卡下所有子卡的余额吗？
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="recycleCardDialog = false">取 消</el-button>
        <el-button type="primary" @click="handleRecleCard">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from "lodash";
import TeamRecharge from "./team_recharge.vue";
import TeamRightDrawer from "./team_rightDrawer.vue";
import teamRechargeDetail from "./team_recharge_detail.vue";
import TeamOrderRecords from "./team_order_Records.vue";
import TeamCardQr from "@/components/QrCode/team-card-qr.vue";
import teamConfigSonCard from "./team_config_sonCard.vue";
import TeamUpdateBlance from "./team_update_blance";
import {
  getStationListApi,
  getFleetCardListApi,
  delParentCardApi,
  recoveryAllSonCardApi,
} from "@/api/teamCard/teamCardList";
export default {
  name: "TeamCardList",
  components: {
    TeamRightDrawer,
    TeamRecharge,
    teamRechargeDetail,
    TeamCardQr,
    TeamOrderRecords,
    teamConfigSonCard,
    TeamUpdateBlance,
  },
  data() {
    return {
      total: 0,
      loading: false,
      queryParams: {
        pageSize: 10,
        pageNum: 1,
        fleetName: "",
        cardNumber: "",
      },
      dateRangeCreatedDate: [],
      // enterpriseList: [], // 油企列表
      stationList: [], // 油站列表
      tableData: [],
      teampListDialog: false, // 添加车队弹框
      teamRechargeDialog: false, // 充值弹框
      teamRechargeDetailDialog: false, // 充值明细弹框
      exportTeamCardQrVisible: false, // 导出二维码弹框
      teamOrderListDialog: false, // 消费记录弹框
      SonCardConfigDialog: false, // 配置子卡弹框
      teamUpdateBlanceDialog: false, // 余额调整抽屉
      operation: "add", // 值有 ： add ,  detail , edit三个
      currentData: {},
      initTeamCardForm: {
        fleetName: "", // 车队名称
        cardNumber: null, // 主卡号
        contacts: "", // 联系人
        phone: "",
        stationId: "",
        useType: 2, // 核销方式 1 司机自动出示核销码   2 第三方和核销机构
        thirdOrganName: "", // 第三方核销机构名称
      },
      currentSelectList: [], // 当前被选中行
      currentExportCardNumber: "", // 当前要导出的车队卡卡号
      delParentCardDialog: false, // 删除车队卡弹框
      recycleCardDialog: false, // 回收子卡弹框
    };
  },
  created() {
    // 油企账号登录
    // if (this.presentEnterprise && this.presentEnterprise.enterpriseId) {
    //   this.getStationList(this.presentEnterprise.enterpriseId);
    // }
    this.getList();
  },
  methods: {
    // 查询油站
    getStationList(val) {
      getStationListApi({ enterpriseId: val }).then((res) => {
        this.stationList = res.rows;
      });
    },

    // 查询列表
    getList() {
      this.loading = true;
      const params = {
        ...this.queryParams,
      };
      if (this.dateRangeCreatedDate && this.dateRangeCreatedDate.length) {
        params.beginTime = this.dateRangeCreatedDate[0];
        params.endTime = this.dateRangeCreatedDate[1];
      }
      getFleetCardListApi(params).then((res) => {
        this.tableData = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
    //  搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.getList();
    },
    //  重置按钮操作
    resetQuery() {
      this.dateRangeCreatedDate = [];
      this.resetForm("queryParamsRef");
      this.handleQuery();
    },

    // 打开新增，编辑，查看抽屉
    openRightDrawer(action, row) {
      this.currentData = cloneDeep(row);
      this.teampListDialog = true;
      this.operation = action;
    },
    // 核销方式格式化
    useTypeformatter(row) {
      if (row.useType === 1) return "司机自动出示核销码";
      if (row.useType === 2)
        return row.thirdOrganName
          ? "第三方核销机构-" + row.thirdOrganName
          : "第三方核销机构";
    },
    // 去充值
    goRecharge(row) {
      this.currentData = cloneDeep(row);
      this.teamRechargeDialog = true;
    },
    // 查看充值明细
    goRechargeDetail(row) {
      this.currentData = cloneDeep(row);
      this.teamRechargeDetailDialog = true;
    },
    // 去消费记录
    goOrderDetail(row) {
      this.currentData = row;
      this.teamOrderListDialog = true;
    },
    // 去余额调整
    goUpdateBlance(row) {
      this.currentData = row;
      this.teamUpdateBlanceDialog = true;
    },
    // 选中行
    handleSelectChange(selection) {
      console.log("车队行", selection);
      this.currentSelectList = selection;
    },

    // 导出二维码
    exportQr() {
      let cardInfo = this.currentSelectList[0];
      this.currentExportCardNumber = cardInfo.cardNumber;
      this.exportTeamCardQrVisible = true;
    },
    downloadImg() {
      this.msgSuccess("导出二维码成功");
    },

    // 配置子卡
    gotoSonCardConfig(row) {
      this.currentData = row;
      this.SonCardConfigDialog = true;
    },
    // 回收
    gotoRecycle(row) {
      this.currentData = cloneDeep(row);
      this.recycleCardDialog = true;
      console.log(row, this.currentData, "回收");
    },

    gotoDeleteParentCard() {
      // 判断所选主卡中是否存在余额不为0
      let isHasBalanceOfParent = this.currentSelectList.some(
        (item) => item.balance > 0
      );
      if (isHasBalanceOfParent) {
        return this.$message.warning(
          "所选中的车队卡中，存在卡的余额不为0, 请先回收车队卡余额"
        );
      }
      this.delParentCardDialog = true;
    },

    // 删除车队卡
    handleDeleteParentCard() {
      let ids = this.currentSelectList.map((item) => item.id).join(",");
      console.log(ids);
      delParentCardApi(ids).then((res) => {
        console.log(res);
        this.msgSuccess("删除车队卡成功");
        this.getList();
        this.delParentCardDialog = false;
      });
    },

    // 回收子卡
    handleRecleCard() {
      console.log(this.currentData);
      recoveryAllSonCardApi(this.currentData.id).then((res) => {
        this.msgSuccess("回收成功");
        this.recycleCardDialog = false;
        this.getList();
      });
    },

    // 关闭弹框
    handleClose() {
      this.delParentCardDialog = false; // 删除车队卡
      this.recycleCardDialog = false; // 回收子卡
    },
  },
};
</script>

<style lang="scss" scoped></style>
